// TaskServiceImpl.java
package com.scuec.groupfive.service.impl;

import com.scuec.groupfive.entity.DailyTask;
import com.scuec.groupfive.entity.StudyPlan;
import com.scuec.groupfive.mapper.StudyPlanMapper;
import com.scuec.groupfive.mapper.TaskMapper;
import com.scuec.groupfive.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private StudyPlanMapper studyPlanMapper;

    @Override
    public List<DailyTask> getTodayTasks(Long userId) {
        return taskMapper.selectTodayTasks(userId);
    }

    @Override
    public int addTask(DailyTask task) {
        // 确保task_date有值
        if (task.getTaskDate() == null) {
            task.setTaskDate(new Date()); // 设置为当前日期时间
        }

        // 自动关联当前日期的长期计划
        if (task.getPlanId() == null) {
            // 使用start_date和end_date来查询
            StudyPlan plan = studyPlanMapper.findPlanByDateRange(
                    task.getUserId(),
                    task.getTaskDate(),
                    task.getTaskDate()
            );
            if (plan != null) {
                task.setPlanId(plan.getPlanId());
            }
        }
        return taskMapper.insertTask(task);
    }

    @Override
    public int updateTask(DailyTask task) {
        return taskMapper.updateTask(task);
    }

    @Override
    public int toggleTaskStatus(Long taskId, Long userId, String status) {
        return taskMapper.updateTaskStatus(taskId, userId, status);
    }

    @Override
    public int deleteTask(Long taskId, Long userId) {
        return taskMapper.deleteTask(taskId, userId);
    }

    @Override
    public Map<String, Object> checkTodayTasksStatus(Long userId) {
        Map<String, Object> result = new HashMap<>();
        int total = taskMapper.countTodayTasks(userId);
        int completed = taskMapper.countCompletedTodayTasks(userId);

        result.put("total", total);
        result.put("completed", completed);
        result.put("allCompleted", total > 0 && total == completed);

        return result;
    }
}